package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"soft-manage/cache"
	"soft-manage/model"
	"strconv"
	"time"
)

func Good(c *gin.Context) {
	title := c.PostForm("title")
	count := c.PostForm("count")
	price := c.PostForm("price")
	if title == "" || count == "" || price == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Good{

		Title: title,
		Count: count,
		Price: price,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "crest" + strconv.Itoa(int(data.ID))
	var article model.Good
	model.DB.Where("id = ?", data.ID).First(&article)
	Josns, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, Josns, time.Hour*3)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func List(c *gin.Context) {
	var articel []model.Good
	redis_key := "lists"
	CraeterData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CraeterData == "" {
		model.DB.First(&articel)
		jonsd, _ := json.Marshal(articel)
		cache.Rdb.Set(cache.Ctx, redis_key, jonsd, time.Hour*3)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": articel,
	})
	return
}
func ListApp(c *gin.Context) {
	var articels []model.Good
	redis_key := "losns"
	CraeterData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CraeterData == "" {
		model.DB.First(&articels)
		jonsd, _ := json.Marshal(articels)
		cache.Rdb.Set(cache.Ctx, redis_key, jonsd, time.Hour*3)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": articels,
	})
	return
}
